﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DAL;
using BLL;
using System.Xml.Linq;

public partial class admin_Media_SlideNews : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
      {
        Session["url_back_admin"] = Request.RawUrl;
        GetPositon();
        LoadPosition();
        ShowData();
        LoadCategory();
      }
    }
    SlideBLL data = new SlideBLL();
    CategoryBLL categoryData = new CategoryBLL();
    ArticleBLL articleData = new ArticleBLL();
    public struct Position
    {
      public string Id;
      public string Name;
      public Position(string id, string name)
      {
        Id = id;
        Name = name;
      }
    }
    public static List<Position> listPosition = new List<Position>();
    public void GetPositon()
    {
      if (listPosition != null) listPosition.Clear();
      XElement xElement = XElement.Load(MyConfig.serverPath + "XML/Config.xml");
      var xPosition = xElement.Descendants("SlideNews").Descendants("Position");
      foreach (XElement item in xPosition)
      {
        Position position = new Position(item.Attribute("Id").Value, item.Element("Name").Value);
        listPosition.Add(position);
      }
    }
    private void LoadPosition()
    {
      dropPosition.Items.Clear();
      foreach (Position item in listPosition)
      {
        dropPosition.Items.Add(new ListItem(item.Name, item.Id));
      }
    }
    private void LoadCategory()
    {
      dropCategory.Items.Clear();
      ShowChild(0, " - - ");
      ListItem itemRoot = new ListItem("Danh mục gốc", "0");
      dropCategory.Items.Insert(0, itemRoot);

      ListItem itemNull = new ListItem("Tất cả", "-1");
      dropCategory.Items.Insert(0, itemNull);
    }
    private void LoadArticle()
    {
      if (dropCategory.Items.Count > 0)
      {
        int id = Convert.ToInt32(dropCategory.SelectedValue);
        List<Article> list = articleData.GetByCategory(id);
        dropArticle.DataSource = list;
        dropArticle.DataValueField = "Id";
        dropArticle.DataTextField = "Title";
        dropArticle.DataBind();
      }
    }
    private void ShowChild(int parentId, string space)
    {
      List<Category> listDataSource = categoryData.GetByParent(parentId);

      foreach (Category item in listDataSource)
      {
        ListItem obj = new ListItem(space + item.Name, item.Id.ToString());
        dropCategory.Items.Add(obj);

        ShowChild(item.Id, space + "- - - ");
      }
    }
    private void ShowData()
    {
      List<Slide> list = new List<Slide>();
      list = data.GetByPosition(Convert.ToInt32(dropPosition.SelectedValue));
      if (dropIsEnable.SelectedIndex != 0)
        list = list.Where(p => p.isEnable == Convert.ToBoolean(dropIsEnable.SelectedValue)).ToList();
      
      gridView.DataSource = GetArticle(list);
      gridView.DataBind();

      //Bo mui ten len xuong dau va cuoi
      if (gridView.Rows.Count > 0)
      {
        gridView.Rows[0].Cells[6].Enabled = false;
        gridView.Rows[gridView.Rows.Count - 1].Cells[5].Enabled = false;
      }
    }
    private List<Article> GetArticle(List<Slide> list)
    {
      List<Article> listArticle = new List<Article>();
      foreach (var item in list)
      {
        Article obj = articleData.GetById(item.Id);
        listArticle.Add(obj);
      }
      return listArticle;
    }
    protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      try
      {
        if (e.Row.RowIndex >= 0) //Bo qua dong dau
        {
          int id = Convert.ToInt32(e.Row.Cells[1].Text);
          if (e.Row.Cells[3].Text == "0") e.Row.Cells[3].Text = "Danh mục gốc";
          else e.Row.Cells[3].Text = categoryData.GetById(Convert.ToInt32(e.Row.Cells[3].Text)).Name;
          bool isEnable = data.GetById(id).isEnable;

          //Icon check
          Image img = new Image();
          foreach (Control item in e.Row.Cells[7].Controls)
          {
            if (item.GetType() == typeof(Image))
            {
              img = (Image)item;
              break;
            }
          }
          if (isEnable)
            img.ImageUrl = "~/Images/check.png";
          else
          {
            img.ImageUrl = "~/Images/an.png";

          }
        }
      }
      catch { }
    }
    protected void dropIsEnable_SelectedIndexChanged(object sender, EventArgs e)
    {
      lbThongBao.Text = "";
      ShowData();
    }
    protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
      lbThongBao.Text = "";
      try
      {
        gridView.PageIndex = e.NewPageIndex;
        ShowData();
      }
      catch { }
    }
    protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
      if ((int)Session["Role"] != 1)
      {
        lbThongBao.Text = "Bạn không có quyền thực hiện thao tác này ! ";
        return;
      }
      try
      {
        lbThongBao.Text = "";
        int id = Convert.ToInt32(gridView.Rows[e.RowIndex].Cells[1].Text);
        data.Delete(id);
        lbThongBao.Text = "Slide đã được xóa";

        ShowData();
      }
      catch (Exception ex)
      {
        lbThongBao.Text = ex.Message;
      }
    }
    private void Enable(bool isEnable)
    {
      foreach (GridViewRow item in gridView.Rows)
      {
        foreach (Control ctrl in item.Cells[0].Controls)
        {
          if (ctrl.GetType() == typeof(CheckBox))
          {
            CheckBox check = (CheckBox)ctrl;
            if (check.Checked)
            {
              int id = Convert.ToInt32(item.Cells[1].Text);
              data.Enable(id, isEnable);
            }
            break;
          }
        }
      }
      ShowData();
    }
    protected void btnVisible_Click(object sender, EventArgs e)
    {
      if ((int)Session["Role"] != 1)
      {
        lbThongBao.Text = "Bạn không có quyền thực hiện thao tác này ! ";
        return;
      }
      lbThongBao.Text = "";
      Enable(false);
    }
    protected void btnEnable_Click(object sender, EventArgs e)
    {
      if ((int)Session["Role"] != 1)
      {
        lbThongBao.Text = "Bạn không có quyền thực hiện thao tác này ! ";
        return;
      }
      lbThongBao.Text = "";
      Enable(true);
    }
    protected void btnXoaChon_Click(object sender, EventArgs e)
    {
      if ((int)Session["Role"] != 1)
      {
        lbThongBao.Text = "Bạn không có quyền thực hiện thao tác này ! ";
        return;
      }
      try
      {
        lbThongBao.Text = "";
        foreach (GridViewRow item in gridView.Rows)
        {
          foreach (Control ctrl in item.Cells[0].Controls)
          {
            if (ctrl.GetType() == typeof(CheckBox))
            {
              CheckBox check = (CheckBox)ctrl;
              if (check.Checked)
              {
                int id = Convert.ToInt32(item.Cells[1].Text);                
                data.Delete(id);
              }
              break;
            }
          }
        }
        ShowData();
        lbThongBao.Text = "Slide đã được xóa";
      }
      catch (Exception ex)
      {
        lbThongBao.Text = ex.Message;
      }
    }
    protected void linkCheckAll_Click(object sender, EventArgs e)
    {
      lbThongBao.Text = "";
      foreach (GridViewRow item in gridView.Rows)
      {
        foreach (Control ctrl in item.Cells[0].Controls)
        {
          if (ctrl.GetType() == typeof(CheckBox))
          {
            CheckBox check = (CheckBox)ctrl;
            check.Checked = true;
            break;
          }
        }
      }
    }
    protected void linkUnCheckAll_Click(object sender, EventArgs e)
    {
      lbThongBao.Text = "";
      foreach (GridViewRow item in gridView.Rows)
      {
        foreach (Control ctrl in item.Cells[0].Controls)
        {
          if (ctrl.GetType() == typeof(CheckBox))
          {
            CheckBox check = (CheckBox)ctrl;
            check.Checked = false;
            break;
          }
        }
      }
    }
    protected void dropCategory_SelectedIndexChanged(object sender, EventArgs e)
    {
      lbThongBao.Text = "";
      LoadArticle();
    }
    protected void btnOk_Click(object sender, EventArgs e)
    {
      if ((int)Session["Role"] != 1)
      {
        lbThongBao.Text = "Bạn không có quyền thực hiện thao tác này ! ";
        return;
      }
      try
      {
        lbThongBao.Text = "";
        if (dropArticle.Items.Count > 0)
        {
          int id = Convert.ToInt32(dropArticle.SelectedValue);
          if (data.CheckExist(id))
          {
            Myfunction.ThongBao(lbThongBao, "Tin này đã có trong danh sách slide");
            return;
          }
          if (data.GetCountItem() >= 10)
          {
            Myfunction.ThongBao(lbThongBao, "Tối đa là 10 tin");
            return;        
          }
          Slide slide = new Slide();
          slide.Sort = data.GetMaxSort(Convert.ToInt32(dropPosition.SelectedValue));
          slide.Position = Convert.ToInt32(dropPosition.SelectedValue);
          slide.Id = Convert.ToInt32(dropArticle.SelectedValue);
          slide.isEnable = true;
          data.Add(slide);
          lbThongBao.Text = "Slide đã được thêm";
          ShowData();
        }
      }
      catch (Exception ex)
      {
        lbThongBao.Text = ex.Message;
      }
    }
    protected void gridView_RowCommand1(object sender, GridViewCommandEventArgs e)
    {
      if ((int)Session["Role"] != 1)
      {
        lbThongBao.Text = "Bạn không có quyền thực hiện thao tác này ! ";
        return;
      }
      try
      {
        lbThongBao.Text = "";
        if (e.CommandName.Equals("Up"))
        {
          int index = Convert.ToInt32(e.CommandArgument);
          int idFirst = Convert.ToInt32(gridView.Rows[index].Cells[1].Text);
          int idSecond = Convert.ToInt32(gridView.Rows[index - 1].Cells[1].Text);

          data.SwapSort(idFirst, idSecond);
        }
        else if (e.CommandName.Equals("Down"))
        {
          int index = Convert.ToInt32(e.CommandArgument);
          int idFirst = Convert.ToInt32(gridView.Rows[index].Cells[1].Text);
          int idSecond = Convert.ToInt32(gridView.Rows[index + 1].Cells[1].Text);

          data.SwapSort(idFirst, idSecond);
        }
        ShowData();

      }
      catch (Exception ex)
      {
        Myfunction.ThongBao(lbThongBao, ex.Message);
      }
    }
    protected void dropPosition_SelectedIndexChanged(object sender, EventArgs e)
    {
      lbThongBao.Text = "";
      ShowData();
    }
}